<template>
  <div class="menu-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>菜单管理</span>
          <el-button type="primary" @click="showCreateDialog">
            <el-icon><Plus /></el-icon>
            新建菜单
          </el-button>
        </div>
      </template>

      <!-- 菜单树形表格 -->
      <el-table 
        :data="menuList" 
        v-loading="loading" 
        style="width: 100%"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="menuName" label="菜单名称" width="200" />
        <el-table-column prop="menuCode" label="菜单编码" width="200" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.type)">
              {{ getTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路径" width="200" />
        <el-table-column prop="component" label="组件" width="200" />
        <el-table-column prop="icon" label="图标" width="100">
          <template #default="scope">
            <el-icon v-if="scope.row.icon">
              <component :is="scope.row.icon" />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="visible" label="显示" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.visible === 1 ? 'success' : 'info'">
              {{ scope.row.visible === 1 ? '显示' : '隐藏' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="editMenu(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="toggleMenuStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              :type="scope.row.visible === 1 ? 'warning' : 'success'"
              @click="toggleMenuVisible(scope.row)"
            >
              {{ scope.row.visible === 1 ? '隐藏' : '显示' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteMenu(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 菜单表单对话框 -->
    <el-dialog 
      v-model="menuDialogVisible" 
      :title="isEdit ? '编辑菜单' : '新建菜单'"
      width="600px"
    >
      <el-form 
        ref="menuFormRef" 
        :model="menuForm" 
        :rules="menuRules" 
        label-width="100px"
      >
        <el-form-item label="菜单名称" prop="menuName">
          <el-input v-model="menuForm.menuName" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单编码" prop="menuCode">
          <el-input v-model="menuForm.menuCode" placeholder="请输入菜单编码" />
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-select v-model="menuForm.type" placeholder="请选择菜单类型">
            <el-option label="目录" :value="1" />
            <el-option label="菜单" :value="2" />
            <el-option label="按钮" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="菜单路径" prop="path" v-if="menuForm.type !== 3">
          <el-input v-model="menuForm.path" placeholder="请输入菜单路径" />
        </el-form-item>
        <el-form-item label="组件路径" prop="component" v-if="menuForm.type === 2">
          <el-input v-model="menuForm.component" placeholder="请输入组件路径" />
        </el-form-item>
        <el-form-item label="菜单图标" prop="icon" v-if="menuForm.type !== 3">
          <el-input v-model="menuForm.icon" placeholder="请输入菜单图标" />
        </el-form-item>
        <el-form-item label="父级菜单" prop="parentId">
          <el-tree-select
            v-model="menuForm.parentId"
            :data="menuTreeOptions"
            :props="menuTreeProps"
            placeholder="请选择父级菜单"
            clearable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="menuForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="menuForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否显示" prop="visible" v-if="menuForm.type !== 3">
          <el-radio-group v-model="menuForm.visible">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="menuDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveMenu">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {menuApi} from "../api/menu";

// 响应式数据
const loading = ref(false)
const menuList = ref([])
const menuDialogVisible = ref(false)
const isEdit = ref(false)

// 菜单表单
const menuFormRef = ref()
const menuForm = reactive({
  id: null,
  menuName: '',
  menuCode: '',
  type: 1,
  path: '',
  component: '',
  icon: '',
  parentId: null,
  sort: 0,
  status: 1,
  visible: 1
})

// 表单验证规则
const menuRules = {
  menuName: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  menuCode: [
    { required: true, message: '请输入菜单编码', trigger: 'blur' },
    { pattern: /^[a-z-]+$/, message: '菜单编码只能包含小写字母和连字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择菜单类型', trigger: 'change' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
}

// 菜单树选项
const menuTreeOptions = computed(() => {
  return [{ id: null, menuName: '顶级菜单', children: menuList.value }]
})

const menuTreeProps = {
  children: 'children',
  label: 'menuName',
  value: 'id'
}

// 生命周期
onMounted(() => {
  loadMenuList()
})

// 加载菜单列表
const loadMenuList = async () => {
  try {
    loading.value = true
    const response = await menuApi.getMenuTree()
    if (response.data.code === 200) {
      menuList.value = response.data.data
    }
  } catch (error) {
    ElMessage.error('加载菜单列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 获取类型标签类型
const getTypeTagType = (type) => {
  const typeMap = {
    1: 'primary',
    2: 'success',
    3: 'warning'
  }
  return typeMap[type] || 'info'
}

// 获取类型标签文本
const getTypeLabel = (type) => {
  const typeMap = {
    1: '目录',
    2: '菜单',
    3: '按钮'
  }
  return typeMap[type] || '未知'
}

// 显示创建对话框
const showCreateDialog = () => {
  isEdit.value = false
  resetMenuForm()
  menuDialogVisible.value = true
}

// 编辑菜单
const editMenu = (menu) => {
  isEdit.value = true
  Object.assign(menuForm, menu)
  menuDialogVisible.value = true
}

// 重置菜单表单
const resetMenuForm = () => {
  menuForm.id = null
  menuForm.menuName = ''
  menuForm.menuCode = ''
  menuForm.type = 1
  menuForm.path = ''
  menuForm.component = ''
  menuForm.icon = ''
  menuForm.parentId = null
  menuForm.sort = 0
  menuForm.status = 1
  menuForm.visible = 1
  menuFormRef.value?.resetFields()
}

// 保存菜单
const saveMenu = async () => {
  try {
    await menuFormRef.value.validate()
    
    if (isEdit.value) {
      const response = await menuApi.getMenuById(menuForm.id);
      if (response.data.code === 200) {
        ElMessage.success('菜单更新成功')
        menuDialogVisible.value = false
        loadMenuList()
      }
    } else {
      const response = await  menuApi.getMenuList(menuForm)
      if (response.data.code === 200) {
        ElMessage.success('菜单创建成功')
        menuDialogVisible.value = false
        loadMenuList()
      }
    }
  } catch (error) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('操作失败')
    }
    console.error(error)
  }
}

// 删除菜单
const deleteMenu = async (menu) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜单"${menu.menuName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await  menuApi.deleteMenu(menu.id);
    if (response.data.code === 200) {
      ElMessage.success('菜单删除成功')
      loadMenuList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

// 切换菜单状态
const toggleMenuStatus = async (menu) => {
  try {
    const newStatus = menu.status === 1 ? 0 : 1

    const response = await  menuApi.updateMenuStatus(menu.id, newStatus);
    if (response.data.code === 200) {
      ElMessage.success('状态更新成功')
      loadMenuList()
    }
  } catch (error) {
    ElMessage.error('状态更新失败')
    console.error(error)
  }
}

// 切换菜单显示
const toggleMenuVisible = async (menu) => {
  try {
    const newVisible = menu.visible === 1 ? 0 : 1
    const response = await  menuApi.updateMenuVisible(menu.id, newVisible);
    if (response.data.code === 200) {
      ElMessage.success('显示状态更新成功')
      loadMenuList()
    }
  } catch (error) {
    ElMessage.error('显示状态更新失败')
    console.error(error)
  }
}
</script>

<style scoped>
.menu-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
